package com.byt.common.util;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.byt.base.utils.ToastUitl;
import com.byt.common.R;
import com.byt.common.bean.VersionInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import androidx.core.content.FileProvider;

/**
 * @author shicm
 * @description：版本管理类；
 * @date 2014年10月10日 下午12:19:15
 */
public class VersionManager {
    /**
     * 防止多次点击检查更新
     */
    private boolean updating;
    private Context context;
    // private long updateTime;
    private Object lock = new Object();
    /**
     * 是否用户自行更新
     */
    private boolean isSilent = true;

    /**
     * 是否取消更新
     */
    private volatile boolean isCancel = false;

    /**
     * 本地保存目录
     */
    private String localDir = Environment.getExternalStorageDirectory().getPath() + "/xmxb/update/";
    /**
     * 本地保存文件名
     */
    private String localFileName;

    /**
     * 进度条
     */
    private ProgressBar downloadBar;
    /**
     * 进度值
     */
    private TextView progressTv;
    private AlertDialog mBuilder;
    private VersionInfo versionInfo;

    // 获取新版本信息
    private static final int HANDLER_DOWNLOAD_PROGRESS = 12;
    private static final int HANDLER_DOWNLOAD_FINISH = 13;
    private static final int HANDLER_DOWNLOAD_ERROR = 14;
    private static final int HANDLER_DOWNLOAD_SIZE = 15;
    private static final int HANDLER_DOWNLOAD_STOP = 16;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            updating = false;
            switch (msg.what) {
                case HANDLER_DOWNLOAD_SIZE:
                    downloadBar.setMax(versionInfo.getFile_size());
                    break;
                case HANDLER_DOWNLOAD_PROGRESS:
                    updating = true;
                    // 更新进度
                    long downLen = msg.arg1;
                    progressTv.setText(downLen * 100 / versionInfo.getFile_size() + "%");
                    downloadBar.setProgress((int) downLen);
                    break;
                case HANDLER_DOWNLOAD_FINISH:
                    // 下载完成,转到安装界面
                    installApkByPath(context, new File(localDir, localFileName).getAbsolutePath());
                    if (null != mBuilder && mBuilder.isShowing()) {
                        mBuilder.dismiss();
                    }
                    break;
                case HANDLER_DOWNLOAD_STOP:
                    if (null != mBuilder && mBuilder.isShowing()) {
                        mBuilder.dismiss();
                    }
                    break;
                case HANDLER_DOWNLOAD_ERROR:
                    String errMsg = (String) msg.obj;
                    if (TextUtils.isEmpty(errMsg)) {
                        ToastUitl.showShort("更新失败");
                    } else {
                        ToastUitl.showShort(errMsg);
                    }
                    if (null != mBuilder && mBuilder.isShowing()) {
                        mBuilder.dismiss();
                    }
                    break;
                default:
                    break;
            }
        }
    };
    private boolean mIsRoot = false;

    public VersionManager(Context context, VersionInfo versionInfo, String localFileName) {
        super();
        this.context = context;
        this.versionInfo = versionInfo;
        this.localFileName = localFileName;
        updateVersion();
    }


    /**
     * 更新版本
     */
    protected void updateVersion() {
        File apkFile = new File(localDir, localFileName);
        /**
         * 如果之前已经下载过就直接安装
         */
        if (apkFile.exists()) { // 如果存在就直接删除，然后重新下载
            // 如果版本号等于最新版本号
            apkFile.delete();
        }
        File dir = new File(localDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        /**
         * 去下载安装
         */
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle("正在升级")
                    .setView(addLayout())
                    .setCancelable(false);
            mBuilder = builder.show();
            if (updating) {
                ToastUitl.showShort("正在下载中");
            } else {
                downloadFile2(apkFile);
            }
        } catch (Exception e) {

        }
    }

    /**
     * 直接文件操作更新进度条；
     */
    private void downloadFile2(final File saveFile) {
        new Thread(new Runnable() {
            @SuppressWarnings("resource")
            @Override
            public void run() {
                InputStream inStream = null;
                FileOutputStream fos = null;
                try {
                    if (versionInfo.getFile_size() > 0) {
                        Log.d("md", "fileSize:" + versionInfo.getFile_size());
                        handler.sendEmptyMessage(HANDLER_DOWNLOAD_SIZE);
                    } else {
                        handler.sendEmptyMessage(HANDLER_DOWNLOAD_ERROR);
                        return;
                    }
                    String fileName = versionInfo.getDownloadUrl()
                            .substring(versionInfo.getDownloadUrl().lastIndexOf("/") + 1);
                    String downloadUrl = versionInfo.getDownloadUrl();
                    URL url = new URL(downloadUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.connect();
                    int length = urlConn.getContentLength();
                    inStream = urlConn.getInputStream();

                    fos = new FileOutputStream(saveFile);
                    byte[] buffer = new byte[1024];
                    int offset;
                    int sum = 0;

                    while ((offset = inStream.read(buffer, 0, 1024)) != -1) {
                        if (isCancel) {
                            // 暂停退出
                            handler.obtainMessage(HANDLER_DOWNLOAD_STOP).sendToTarget();
                            return;
                        }
                        fos.write(buffer, 0, offset);
                        sum += offset;
                        handler.obtainMessage(HANDLER_DOWNLOAD_PROGRESS, sum, 0).sendToTarget();
                    }
                    if (sum == versionInfo.getFile_size()) {
                        handler.sendEmptyMessage(HANDLER_DOWNLOAD_FINISH);
                    } else {
                        handler.obtainMessage(HANDLER_DOWNLOAD_ERROR, "下载文件不匹配！").sendToTarget();
                    }
                } catch (Exception e) {
                    handler.obtainMessage(HANDLER_DOWNLOAD_ERROR, "文件下载失败！").sendToTarget();
                } finally {
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                        if (inStream != null) {
                            inStream.close();
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }).start();
    }


    /**
     * 由apk路径直接跳到安装界面
     */
    public void installApkByPath(Context context, String absPath) {
        String cmd = "chmod 777 " + absPath;
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            //provider authorities
            Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", new File(absPath));
            //Granting Temporary Permissions to a URI
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.parse("file://" + absPath), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    @SuppressLint("ResourceType")
    public RelativeLayout addLayout() {
        RelativeLayout relativeLayout = new RelativeLayout(context);
        TextView textView = new TextView(context);
        textView.setId(1);
        textView.setTextSize(15);
        textView.setTextColor(Color.BLACK);
        textView.setText("下载进度:");
        RelativeLayout.LayoutParams layoutParams1 =
                new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
        layoutParams1.setMargins(10, 10, 10, 10);
        relativeLayout.addView(textView, layoutParams1);

        progressTv = new TextView(context);
        progressTv.setId(2);
        progressTv.setTextSize(15);
        progressTv.setTextColor(Color.BLACK);
        RelativeLayout.LayoutParams layoutParams2 =
                new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams2.addRule(RelativeLayout.RIGHT_OF, 1);
        layoutParams2.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        layoutParams2.setMargins(0, 10, 10, 10);
        relativeLayout.addView(progressTv, layoutParams2);

        downloadBar = new ProgressBar(context);
        downloadBar.setId(3);
        downloadBar.setMax(100);
        downloadBar.setProgress(25);
        downloadBar.setMinimumHeight(20);
        ProgressBeanUtil.setFieldValue(downloadBar, "mOnlyIndeterminate", new Boolean(false));
        downloadBar.setIndeterminate(false);
        downloadBar.setProgressDrawable(
                context.getResources().getDrawable(R.drawable.progress_bar_states));
        // downloadBar.setProgressDrawable(context.getResources().getDrawable(android.R.drawable.progress_horizontal));
        downloadBar.setIndeterminateDrawable(
                context.getResources().getDrawable(android.R.drawable.progress_indeterminate_horizontal));
        RelativeLayout.LayoutParams layoutParams3 =
                new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 20);

        layoutParams3.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        layoutParams3.addRule(RelativeLayout.BELOW, 1);
        layoutParams3.setMargins(10, 10, 10, 10);
        relativeLayout.addView(downloadBar, layoutParams3);
        return relativeLayout;
    }

    public void setInstallMode(boolean isRoot) {
        mIsRoot = isRoot;
    }

}
